package gmodel

import (
	"context"
	"fmt"
	"gitee.com/851537/gmodel/rds"
	"github.com/andeya/ameda"
	"github.com/redis/go-redis/v9"
)

type IRedisGeo interface {
	IBase

	//impl by son
	RedisGeoName() string
	RedisGeoKey() interface{}
	GetLat() float64
	GetLot() float64

	//SetLatLot(lat, lot float64)
}

type BaseRedisGeo struct {
	//Lot float64 `orm:"-" json:"lot"` //经度
	//Lat float64 `orm:"-" json:"lat"` //纬度
}

func (this *BaseRedisGeo) RedisGeoAdd(child IRedisGeo) error {
	location := &redis.GeoLocation{}
	location.Name = fmt.Sprintf("%v", child.RedisGeoKey())
	location.Latitude = child.GetLat()
	location.Longitude = child.GetLot()
	_, err := rds.ClientIns().GeoAdd(context.Background(), child.RedisGeoName(), location).Result()
	return err

}

//func (this *BaseRedisGeo) RedisGeoGet(child IRedisGeo) error {
//	//hlog.Debug(child.RedisGeoName(), fmt.Sprintf("%v", child.RedisGeoKey()))
//	pos, err := NewRedisDaoV2().GeoPos(child.RedisGeoName(), fmt.Sprintf("%v", child.RedisGeoKey())).Result()
//	if err == nil && len(pos) > 0 {
//		child.SetLatLot(pos[0].Latitude, pos[0].Longitude)
//	}
//	return err
//}

func (this *BaseRedisGeo) RedisGeoDel(child IRedisGeo) (int64, error) {
	return rds.ClientIns().ZRem(context.Background(), child.RedisGeoName(), fmt.Sprintf("%v", child.RedisGeoKey())).Result()
}

// default unit:m,include radius,return distance
// sort:1.ASC 2.DESC
func (this *BaseRedisGeo) RedisGeoRadius(child IRedisGeo, lot, lat float64, radius, count int, sort int8) ([]redis.GeoLocation, error) {
	query := &redis.GeoRadiusQuery{}
	query.Unit = "m"
	switch sort {
	case 1:
		query.Sort = "ASC"
	default:
		query.Sort = "DESC"
	}
	query.Radius = float64(radius)
	query.WithCoord = true
	query.WithDist = true
	query.WithGeoHash = true
	query.Count = count
	return rds.ClientIns().GeoRadius(context.Background(), child.RedisGeoName(), lot, lat, query).Result()
}

func (this *BaseRedisGeo) RedisGeoRadiusIds(child IRedisGeo, lot, lat float64, radius, count int, sort int8) ([]int64, error) {
	list, err := this.RedisGeoRadius(child, lot, lat, radius, count, sort)
	if err != nil {
		return nil, err
	}
	ids := make([]int64, 0)
	for _, v := range list {
		id, _ := ameda.StringToInt64(v.Name)
		ids = append(ids, id)
	}
	return ids, nil
}
